package org.ting.book.controller;

import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.ting.book.component.ResultFail;
import org.ting.book.component.ResultGenerator;
import org.ting.book.component.ResultSuccess;
import org.ting.book.model.Result;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Random;

@RestController
@RequestMapping("/captcha")
@Scope("session") //设置为会话作用域保证能够获取到生成的验证码
public class EmailCaptcha {
    //类变量 todo
    private static final String username = "2275980533@qq.com";
    private static final String password = "ifgiybqpzqzoeafg";

    private static final Properties props;

    private static final Session session;

    private static final Message message;

    private String captcha = ""; //验证码
    private long createTime = -1; //创建时间
    private final int lifespan = 5 * 60 * 1000; //有效时间单位ms

    ResultGenerator success = new ResultSuccess();
    ResultGenerator fail = new ResultFail();

    static {
        // 配置邮件服务器属性
        props = new Properties();
        props.put("mail.smtp.host", "smtp.qq.com");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.starttls.enable", "true");

        // 创建会话对象
        session = Session.getInstance(props,
                new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

        // 创建邮件消息
        message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(username));
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
    //发送验证码
    @RequestMapping("/send")
    public Result<?> sendCaptcha(String userName) {
        //生成验证码
        if(captcha.isEmpty() || createTime + lifespan < System.currentTimeMillis()) {
            captcha = String.valueOf(1000 + new Random().nextInt(9000));
            createTime = System.currentTimeMillis();
        }

        try {
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(userName));
            message.setSubject("验证码");
            message.setText("您的验证码是：" + captcha +" 有效期为5分钟！");

            // 发送邮件
            Transport.send(message);

            //System.out.println("Email sent successfully!");

        } catch (AddressException e) {
            // 邮箱地址格式不正确
            return fail.getResult("您输入的邮箱有误");
        } catch (MessagingException e) {
            return fail.getResult("发送验证码失败，请检查邮箱是否正确");
        }
        return success.getResult();
    }
    //验证验证码
    @RequestMapping("/verify")
    public Result<?> verify(String captcha) {
        if(!captcha.equals(this.captcha)) {
            return fail.getResult("验证码错误");
        }
        if(createTime + lifespan < System.currentTimeMillis()) {
            return fail.getResult("验证码过期，请重新获取");
        }
        return success.getResult();
    }
}
